package com.laoxu.test.sqlitedemo.config;

import org.apache.ibatis.lang.UsesJava8;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.time.LocalDateTime;

/**
 * 数据库：long <--> java: LocalDateTime 转换处理器
 *
 * @author kalong
 * @date 2021/6/9
 */
@UsesJava8
public class LocalDateTimeTypeStringHandler extends BaseTypeHandler<LocalDateTime> {

    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, LocalDateTime parameter, JdbcType jdbcType)
            throws SQLException {
        ps.setString(i, Java8DateUtils.getDateStrWithFormate(parameter, Java8DateUtils.DATE_TIME_PATTERN));
    }

    @Override
    public LocalDateTime getNullableResult(ResultSet rs, String columnName) throws SQLException {
        String timestamp = rs.getString(columnName);
        return Java8DateUtils.convertDateStrToLocalDateTime(timestamp, Java8DateUtils.DATE_TIME_PATTERN);
    }

    @Override
    public LocalDateTime getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        String timestamp = rs.getString(columnIndex);
        return Java8DateUtils.convertDateStrToLocalDateTime(timestamp, Java8DateUtils.DATE_TIME_PATTERN);
    }

    @Override
    public LocalDateTime getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
        String timestamp = cs.getString(columnIndex);
        return Java8DateUtils.convertDateStrToLocalDateTime(timestamp, Java8DateUtils.DATE_TIME_PATTERN);
    }

}
